package common.util;

import common.CommonConstants;
import common.model.WebUser;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;

/**
 * Entity Bean Util
 * 
 * @author shousuke
 */
public class EbUtil {

    public static Object invokeControllerMethod(String controllerName, String controllerClass, String controllerMethod, Object... methodArgs) {
        FacesContext context = FacesContext.getCurrentInstance();
        Object controller = context.getApplication().getELResolver().getValue(context.getELContext(), null, controllerName);
        try {
            Class<?> cntrlrClass = Class.forName(controllerClass);
            Class<?>[] paramClass = new Class<?>[methodArgs.length];
            for (int i = 0; i < methodArgs.length; i++) {
                paramClass[i] = methodArgs[i].getClass();
            }
            Method cntrlrMethod = cntrlrClass.getMethod(controllerMethod, paramClass);
            return cntrlrMethod.invoke(controller, methodArgs);
        } catch (ClassNotFoundException e) {
            throw new FacesException(e);
        } catch (NoSuchMethodException e) {
            throw new FacesException(e);
        } catch (IllegalAccessException e) {
            throw new FacesException(e);
        } catch (InvocationTargetException e) {
            throw new FacesException(e);
        }
    }

    public static <T> T getEntityBeanFromRequest(String controllerName, String controllerClass, String controllerMethod, String reqParam) {
        String reqParamVal = FacesUtil.getRequestParameter(reqParam);
        if (reqParamVal == null) {
            return null;
        }
        Long id = Long.parseLong(reqParamVal);
        return (T) invokeControllerMethod(controllerName, controllerClass, controllerMethod, id);
    }

    public static WebUser getUserFromRequest(String reqParam) {
        return (WebUser) getEntityBeanFromRequest("webUser", "common.web.WebUserController", "findEntityBean", reqParam);
    }

    public static WebUser getUserFromSession() {
        return (WebUser) FacesUtil.getSessionMapValue(CommonConstants.SSN_CUR_WEB_USER);
    }

    public static WebUser getUser(String reqParam) {
        WebUser user = getUserFromRequest(reqParam);
        if (user == null) {
            user = getUserFromSession();
        }
        return user;
    }

    public static WebUser getUser() {
        return getUser(CommonConstants.REQ_CUR_WEB_USER);
    }
}
